package edu.tyut.game.ui.person

import android.graphics.Color
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.FileUtils
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.hutool.core.io.FileUtil
import cn.hutool.core.io.file.FileSystemUtil
import com.bumptech.glide.Glide
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.ValueFormatter
import com.google.gson.Gson
import com.luck.picture.lib.basic.PictureContentResolver.openInputStream
import edu.tyut.game.GameApplication
import edu.tyut.game.databinding.FragmentPersonCenterBinding
import edu.tyut.game.logic.model.Feedback
import edu.tyut.game.logic.model.FriendCircle
import edu.tyut.game.logic.model.UserTotalRoundsRank
import edu.tyut.game.logic.model.UserWinRateRank
import edu.tyut.game.logic.network.ServiceCreator
import edu.tyut.game.ui.community.PostImageViewAdapter
import edu.tyut.game.ui.game.FlowerActivity
import edu.tyut.game.ui.learn.LearnViewModel
import edu.tyut.game.utils.LogUtils
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.util.Timer
import java.util.TimerTask


class PersonFragment : Fragment() {

    private val tag = this::class.java.name

    private var _binding: FragmentPersonCenterBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    private val viewModel by lazy {
        ViewModelProvider(this)[PersonViewModel::class.java]
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentPersonCenterBinding.inflate(inflater, container, false)
        val root: View = binding.root

        binding.username.text = GameApplication.loginUser?.username
        binding.gender.text = GameApplication.loginUser?.gender

        // ============= 观察者 =================
        val url = "${ServiceCreator.BASE_URL}${GameApplication.loginUser!!.avatarPath}"
        LogUtils.d(tag, url)
        Glide.with(this.requireContext()).load(url).into(binding.iconImage)
        viewModel.resHeadIconUpdate.observe(viewLifecycleOwner){ res ->
            val isSuccess = res.getOrNull()
            if (isSuccess == true){
                LogUtils.d(tag, "头像修改成功")
                val urlNew = "${ServiceCreator.BASE_URL}${GameApplication.loginUser!!.avatarPath}"
                LogUtils.d(tag, urlNew)
                Glide.with(this.requireContext()).load(urlNew).into(binding.iconImage)
            }
        }
        // 游戏排行观察者 TODO GO
        viewModel.resWinRateRank.observe(viewLifecycleOwner){ res ->
            val winRateRank = res.getOrNull()
            winRateRank?.let {
                setData(binding.bar1, "胜率", it)
            }
        }
        viewModel.resTotalRoundsRank.observe(viewLifecycleOwner){ res ->
            val totalRounds = res.getOrNull()
            totalRounds?.let {
                setData(binding.bar2, "总局数", it)
            }
        }
        // =====================================
        val pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            // Callback is invoked after the user selects a media item or closes the
            // photo picker.
            if (uri != null) {
                Log.d("PhotoPicker", "Selected URI: $uri")
                headIconUpdate(uri)
            } else {
                Log.d("PhotoPicker", "No media selected")
            }
        }
        // 头像更换
        binding.iconImage.setOnClickListener {
            pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
        }
        // ================================

        // 游戏数据曲线
        // val list = mutableListOf<Entry>()
        // list.add(Entry(0F, 7F))
        // list.add(Entry(1F, 10F))
        // list.add(Entry(2F, 12F))
        // list.add(Entry(3F, 6F))
        // list.add(Entry(4F, 3F))
        // val lineDataSet = LineDataSet(list, "飞花令")
        //
        // val list1 = mutableListOf<Entry>()
        // list1.add(Entry(1F, 8F))
        // list1.add(Entry(2F, 20F))
        // list1.add(Entry(3F, 13F))
        // list1.add(Entry(4F, 8F))
        // list1.add(Entry(5F, 6F))
        // val lineDataSet1 = LineDataSet(list1, "汉字听写")
        // lineDataSet1.setCircleColor(Color.rgb(25, 25, 24))
        // lineDataSet1.color = Color.parseColor("#123456")
        //
        // val lineData = LineData(lineDataSet)
        // lineData.addDataSet(lineDataSet1)
        // binding.line.data = lineData
        //
        // binding.about.setOnClickListener {
        //     AboutActivity.actionStart(this.requireContext())
        // }
        //
        // binding.feedback.setOnClickListener {
        //     FeedbackActivity.actionStart(this.requireContext())
        // }
        var flag = false
        binding.switchPic.setOnClickListener {
            if (flag) {
                binding.bar1.visibility = View.VISIBLE
                binding.bar2.visibility = View.GONE
            }else{
                binding.bar1.visibility = View.GONE
                binding.bar2.visibility = View.VISIBLE
            }
            flag = !flag
        }
        setLegend(binding.bar1)
        setLegend(binding.bar2)
        setDescription(binding.bar1)
        setDescription(binding.bar2)
        setXAxis(binding.bar1)
        setXAxis(binding.bar2)
        setYAxis(binding.bar1)
        setYAxis(binding.bar2)

        val handler = SetValueHandler(Looper.getMainLooper())
        val timer = Timer()
        timer.schedule(object : TimerTask() {
            override fun run() {
                handler.sendEmptyMessage(SET_VALUE_CODE)
            }
        }, 0, 5000)
        return root
    }

    // ============ 图表 ===================
    private fun setLegend(bar: BarChart) {
        if (bar == binding.bar1) {
            val legend = bar.legend
            legend.formSize = 12F // 图例图形大小
            legend.textSize = 15F
            // legend.setDrawInside(true)
            // legend.orientation = Legend.LegendOrientation.VERTICAL
            // legend.horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
            // legend.verticalAlignment = Legend.LegendVerticalAlignment.TOP
            // legend.yOffset = 55F
            // legend.xOffset = 30F
        }else{
            // bar2
            val legend = bar.legend
            legend.formSize = 12F // 图例图形大小
            legend.textSize = 15F
            // legend.setDrawInside(true)
            // legend.orientation = Legend.LegendOrientation.VERTICAL
            // legend.horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
            // legend.verticalAlignment = Legend.LegendVerticalAlignment.TOP
            // legend.yOffset = 55F
            // legend.xOffset = 30F
        }
    }

    private fun setDescription(bar: BarChart) {
        if (bar == binding.bar1) {
            val description = bar.description
            // 设置文字
            description.text = "飞花令胜率排行榜🎉🎊🏅🏆🥇🥈🥉"
            // 设置字体大小
            description.textSize = 18F
            description.textColor = Color.rgb(0, 0, 0)
            // 获取屏幕中间 x轴 的像素坐标
            val widthPixels = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                requireActivity().windowManager.currentWindowMetrics.bounds.width()
            } else {
                requireActivity().windowManager.defaultDisplay.width
            }
            // val x = widthPixels / 2F
            val x = widthPixels / 1.15F
            Log.d(tag, x.toString())
            description.setPosition(x, 55F)
            // description.textColor = Color.rgb(45, 12, 220)
            description.typeface = Typeface.DEFAULT_BOLD
        }else{
            val description = bar.description
            // 设置文字
            description.text = "飞花令总局数排行榜🎉🎊🏅🏆🥇🥈🥉"
            // 设置字体大小
            description.textSize = 18F
            description.textColor = Color.rgb(233, 30, 99)
            // 获取屏幕中间 x轴 的像素坐标
            val widthPixels = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                requireActivity().windowManager.currentWindowMetrics.bounds.width()
            } else {
                requireActivity().windowManager.defaultDisplay.width
            }
            // val x = widthPixels / 2F
            val x = widthPixels / 1.15F
            Log.d(tag, x.toString())
            description.setPosition(x, 55F)
            description.typeface = Typeface.DEFAULT_BOLD
        }
    }

    private fun setXAxis(bar: BarChart) {
        if (bar == binding.bar1) {
            val xAxis = bar.xAxis
            xAxis.position = XAxis.XAxisPosition.BOTTOM
            xAxis.valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
                    return "第${value.toInt()}名"
                }
            }
            // x 轴坐标线消失
            // xAxis.setDrawAxisLine(false)
            // x 轴垂直坐标线消失
            // xAxis.setDrawGridLines(false)
            // x 轴标签的大小
            xAxis.textSize = 10F
            xAxis.labelCount = 5
            // xAxis.setCenterAxisLabels(false)
            xAxis.axisMinimum = 1F
            xAxis.axisMaximum = 5F
        }else{
            val xAxis = bar.xAxis
            xAxis.position = XAxis.XAxisPosition.BOTTOM
            xAxis.valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
                    return "第${value.toInt()}名"
                }
            }
            // x 轴坐标线消失
            // xAxis.setDrawAxisLine(false)
            // x 轴垂直坐标线消失
            // xAxis.setDrawGridLines(false)
            // x 轴标签的大小
            xAxis.textSize = 10F
            xAxis.labelCount = 5
            // xAxis.setCenterAxisLabels(false)
            xAxis.axisMinimum = 1F
            xAxis.axisMaximum = 5F
        }
    }

    private fun setYAxis(bar: BarChart) {
        if (bar == binding.bar1) {
            // 左边的y轴
            val yAxisLeft = bar.axisLeft
            yAxisLeft.valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
                    return "${String.format("%.2f", value * 100)}%"
                }
            }
            // yAxisLeft.valueFormatter = object : ValueFormatter() {
            //     override fun getFormattedValue(value: Float): String {
            //         return "${String.format("%.2f", value * 100)}%"
            //     }
            // }

            // 右边的y轴
            val yAxisRight = bar.axisRight
            yAxisRight.isEnabled = false
            // yAxisRight.valueFormatter = object : ValueFormatter() {
            //     override fun getFormattedValue(value: Float): String {
            //         return "${value.toInt()}局"
            //     }
            // }
        }else{
            // 左边的y轴
            val yAxisLeft = bar.axisLeft
            yAxisLeft.valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
                    return "${value.toInt()}局"
                }
            }
            // yAxisLeft.valueFormatter = object : ValueFormatter() {
            //     override fun getFormattedValue(value: Float): String {
            //         return "${String.format("%.2f", value * 100)}%"
            //     }
            // }

            // 右边的y轴
            val yAxisRight = bar.axisRight
            yAxisRight.isEnabled = false
            // yAxisRight.valueFormatter = object : ValueFormatter() {
            //     override fun getFormattedValue(value: Float): String {
            //         return "${value.toInt()}局"
            //     }
            // }
        }
    }

    private fun <T> setData(bar: BarChart, label: String, list: List<T>) {
        if (bar == binding.bar1) {
            val barEntryList = mutableListOf<BarEntry>()
            for (i in list.indices) {
                val winRateRank = list[i] as UserWinRateRank
                LogUtils.d(tag, i.toString())
                barEntryList.add(BarEntry(i.toFloat(), winRateRank.winRate.toFloat()))
            }
            // ==================
            val set = BarDataSet(barEntryList, label)
            // 设置柱子的颜色
            set.color = Color.rgb(128, 34, 117)
            set.valueTextSize = 10F
            set.valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
                    return "${String.format("%.2f", value * 100)}%"
                }
            }
            val barData = BarData(set)
            // 设置柱子的宽度
            barData.barWidth = 0.3F

            // 参数1：距左边的距离（开始会偏移一个组的距离）
            // 参数二：组与组之间的间距
            // 参数三：一组柱块之中每个之间的距离
            // barData.groupBars(1F, 0.2F, 0F);
            bar.data = barData
        }else{
            val barEntryList = mutableListOf<BarEntry>()
            for (i in list.indices) {
                val totalRounds = list[i] as UserTotalRoundsRank
                barEntryList.add(BarEntry(i.toFloat(), totalRounds.totalRounds.toFloat()))
            }
            // ==================
            val set = BarDataSet(barEntryList, label)
            // 设置柱子的颜色
            set.color = Color.rgb(148, 68, 173)
            set.valueTextSize = 10F
            set.valueFormatter = object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
                    return "${value.toInt()}局"
                }
            }
            val barData = BarData(set)
            // 设置柱子的宽度
            barData.barWidth = 0.5F

            // 参数1：距左边的距离（开始会偏移一个组的距离）
            // 参数二：组与组之间的间距
            // 参数三：一组柱块之中每个之间的距离
            // barData.groupBars(1F, 0.2F, 0F);
            bar.data = barData
        }
    }
    // ============ 图表 ===================
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    private fun headIconUpdate(uri: Uri) {
        val builder = MultipartBody.Builder().setType(MultipartBody.FORM)
        val inputStream = openInputStream(context, uri)
        val requestFile: RequestBody =
            RequestBody.create(
                MediaType.parse("image/*"),
                inputStream!!.readBytes()
            ) // 图片文件不能超过2G
        val str = uri.toString()
        var name = str.substring(str.lastIndexOf("/") + 1)
        if (!name.contains(".")) name = "$name.jpg"
        builder.addFormDataPart("file", name, requestFile)
        inputStream.close()
        builder.addFormDataPart("uid", (GameApplication.loginUser?.id ?: 1).toString())
        val parts = builder.build().parts()
        // TODO 头像上传成功
        LogUtils.d(tag, "头像上传成功...")
        viewModel.headIconUpdate(parts)
    }
    private inner class SetValueHandler(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            if (msg.what == SET_VALUE_CODE) {
                viewModel.getWinRateRank(0)
                viewModel.getTotalRoundsRank(0)
            }
        }
    }
    companion object{
        private const val SET_VALUE_CODE = 0x111
    }
}